<?php

namespace App\Model;

use App\Exceptions\BizException;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $table = 'order';

    CONST PAY_STATUS_0 = 0; // 未支付
    CONST PAY_STATUS_1 = 1;

    public static $payStatusLabels = [
        self::PAY_STATUS_0 => '未支付',
        self::PAY_STATUS_1 => '已支付',
    ];

    CONST STATUS_01 = -1;
    CONST STATUS_0 = 0;
    CONST STATUS_1 = 1;

    public static $statusLabels = [
        self::STATUS_01 => '已删除',
        self::STATUS_0 => '未处理',
        self::STATUS_1 => '已发货',
    ];

    public function user()
    {
        return $this->hasOne('App\Model\Users', 'id', 'uid');
    }

    public function orderDetails()
    {
        return $this->hasMany('App\Model\OrderDetail');
    }

    /**
     * 创建订单
     *
     * @param $openid
     * @param $cartGoods
     * @param $agent
     * @param $user
     * @param $params
     * @return mixed
     * @throws BizException
     */
    public static function createOrder($openid, $cartGoods, $agent, $user, $params)
    {
        // 收货地址
        $address = UserAddress::find($params['address_id']);
        $address['province'] = Province::where('id', $address['province_id'])->value('name');
        $address['city'] = City::where('id', $address['city_id'])->value('name');

        $totalCost = 0;
        $totalMoney = 0;
        $cartGoods = $cartGoods ? : [];
        $list = Goods::where('status', 1)
            ->where('agent_id', $agent['id'])
            ->whereIn('id', array_keys($cartGoods))
            ->get();
        if (empty($list))
            throw new BizException('无商品');
        foreach ($list as $goods) {
            $totalCost += $goods['cost'] * $cartGoods[$goods['id']];
            $totalMoney += $goods['price'] * $cartGoods[$goods['id']];
        }

        // 生成订单
        $order_id = self::insertGetId([
            'agent_id' => $agent['id'],
            'order_num' => date('ymdHis') . mt_rand(1000, 9999),
            'uid' => $user->id,
            'openid' => $openid,
            'name' => $address['name'],
            'mobile' => $address['mobile'],
            'address' => $address['province'] . $address['city'] . $address['district'] . $address['detail'],
            'remark' => empty($params['remark']) ? '' : $params['remark'],
            'num' => count($list),
            'cost' => $totalCost,
            'money' => $totalMoney,
            'pay_status' => self::PAY_STATUS_0,
            'status' => self::STATUS_0,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);

        // 订单详情
        $orderDetails = [];
        foreach ($list as $goods) {
            $orderDetails[] = [
                'order_id' => $order_id,
                'agent_id' => $agent['id'],
                'uid' => $user->id,
                'goods_id' => $goods['id'],
                'supplier_id' => $goods['supplier_id'],
                'name' => $goods['name'],
                'pic' => $goods['pic'],
                'cost' => $goods['cost'],
                'origin_price' => $goods['origin_price'],
                'price' => $goods['price'],
                'num' => $cartGoods[$goods['id']],
                'money' => $goods['price'] * $cartGoods[$goods['id']],
            ];
        }
        OrderDetail::insert($orderDetails);

        return $order_id;
    }

    /**
     * 支付成功回调
     *
     * @param $order
     */
    public static function paySuccess($order)
    {
        self::where('id', $order['id'])->update([
            'pay_status' => Order::PAY_STATUS_1,
            'pay_time' => date('Y-m-d H:i:s'),
        ]);
    }

    public static function getFinanceInfo($agent_id, $start, $end)
    {
        $row = [];

        // 订单数
        $row['order_num'] = Order::where('agent_id', $agent_id)
            ->where('pay_status', 1)
            ->where('created_at', '>', $start)
            ->where('created_at', '<=', $end . ' 23:59:59')
            ->count();

        // 用户数
        $userIds = Order::select(['uid'])
            ->where('agent_id', $agent_id)
            ->where('pay_status', 1)
            ->where('created_at', '>', $start)
            ->where('created_at', '<=', $end . ' 23:59:59')
            ->groupBy('uid')
            ->get();
        $row['user_num'] = count($userIds);

        // 成本
        $row['cost'] = Order::where('agent_id', $agent_id)
                ->where('pay_status', 1)
                ->where('created_at', '>', $start)
                ->where('created_at', '<=', $end . ' 23:59:59')
                ->sum('cost') + 0;

        // 销售额
        $row['sale'] = Order::where('agent_id', $agent_id)
                ->where('pay_status', 1)
                ->where('created_at', '>', $start)
                ->where('created_at', '<=', $end . ' 23:59:59')
                ->sum('money') + 0;

        // 利润
        $row['profit'] = $row['sale'] - $row['cost'];

        return $row;
    }
}
